import scrapy
import requests,json
from bid.items import BidItem
from bid.tools import *


class ZhejiangSpider(scrapy.Spider):
    name = 'zhejiang'
    allowed_domains = ['zjpubservice.zjzwfw.gov.cn/']
    start_urls = ['http://zjpubservice.zjzwfw.gov.cn/']
    url = 'http://zjpubservice.zjzwfw.gov.cn/inteligentsearch/rest/inteligentSearch/getFullTextData'
    t_dic ={
        '002001008':['工程建设-项目登记信息','0'],
        '002001001':['工程建设-招标公告','1'],
        '002001002':['工程建设-资质预审公告','2'],
        '002001006':['工程建设-澄清修改公告','2'],
        '002001007':['工程建设-资质预审结果公告','2'],
        '002001003':['工程建设-开标结果公告','2'],
        '002001004':['工程建设-中标候选人公示','2'],
        '002001005':['工程建设-中标结果人公示','3'],
        '002001009':['工程建设-合同订立信息','3'],
        '002002001':['政府采购-采购公告','1'],
        '002002005':['政府采购-竞争性磋商公告','1'],
        '002002006':['政府采购-竞争性谈判公告','1'],
        '002002002':['政府采购-中标成交公告','3'],
        '002002003':['政府采购-更正公告','2'],
        '002002004':['采购合同-更正公告','2'],
        '002007001':['其他交易-交易公告','1'],
        '002007002':['其他交易-交易结果','3'],
    }
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36'}
    msg =[]
    def start_requests(self):
        for page in range(1,999999):
            import time
            data = '{"token":"","pn":%s,"rn":12,"sdt":"","edt":"","wd":"","inc_wd":"","exc_wd":"","fields":"title","cnum":"001","sort":"{\\"webdate\\":\\"0\\"}","ssort":"title","cl":200,"terminal":"","condition":[{"fieldName":"categorynum","isLike":true,"likeType":2,"equal":"002"},{"fieldName":"infoc","isLike":true,"likeType":2,"equal":"33"}],"time":[{"fieldName":"webdate","startTime":"2020-12-06 00:00:00","endTime":"%s 23:59:59"}],"highlights":"","statistics":null,"unionCondition":null,"accuracy":"","noParticiple":"0","searchRange":null,"isBusiness":"1"}'%((page-1)*12,time.strftime('%Y-%m-%d'))
            res = requests.post(url=self.url,data=data,headers=self.headers).json()
            ls = res['result']['records']
            last_page = res['result']['totalcount']//20+1
            print(ls)
            if page > last_page:
                break
            for l in ls:
                item = {}
                item['link'] = 'http://zjpubservice.zjzwfw.gov.cn' + l['linkurl']
                key = item['link'].split('/')[-3]
                if key not in self.t_dic:
                    continue
                item['title'] = l['title']
                item['time'] = l['infodate'][:10]
                item['classification'] = '浙江-'+self.t_dic[key][0]
                item['typ']=self.t_dic[key][-1]
                if redis_dupefilter(item) or item['time'].startswith('2021'):
                    self.msg.append(page)
                    break
                yield scrapy.Request(url=item['link'], callback=self.parse, meta={'item': item})
                # break
            if page in self.msg:
                print('完成')
                break
            time.sleep(len(ls))

    def parse(self, response):
        item = BidItem()
        item.update(response.meta['item'])
        item['content'] = get_content(response.text, '//div[@class="con"]')
        item = get_field(dict(item))
        yield item